package com.example.converter;

import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @author GYL
 * @dateTime 2020/4/20-17:35
 * @description
 */
public class CustomResponseBodyConverter<T> implements Converter<ResponseBody, T> {
  private Type type;
  private SpecialParse specialParse;
  
  public CustomResponseBodyConverter(Type type,SpecialParse specialParse){
    this.type=type;
    this.specialParse=specialParse;
  }
  
  @Override
  public T convert(ResponseBody value) throws IOException {
    // 解析body数据
    String body=value.string();
    try {
      Class tClass = TypeToken.get(type).getRawType();
      T t = (T) tClass.newInstance();
      String[] strs = StringHelper.split(body, "|");
      for (String s : strs) {
        String[] ss = StringHelper.split(s, "=");
        Field declaredField = tClass.getDeclaredField(ss[0]);
        declaredField.setAccessible(true);
        declaredField.set(t, ss[1]);
      }
      return t;
    } catch (Exception e){
      throw new IOException();
    }finally {
      value.close();
    }
  }
}
